package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.po.WxUserInfo;
import com.example.demo.service.WxPayService;
import com.example.demo.util.HttpClientUtil;
import com.example.demo.util.WxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/wxInterface")
public class WxController {

    private static String appid ="wx0433b7474fdfe2d4";
    private static String appSercret= "22425437072c294178e4edeca2cabb23";

    public static String tokenUrl ="https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    WxPayService wxPayService;

    @RequestMapping("/getToken")
    public String WxGetToken(@RequestParam(value = "code")String code){
        StringBuffer url = new StringBuffer();
        url.append(tokenUrl).append("?appid=").append(appid)
                .append("&secret=").append(appSercret)
                .append("&js_code=").append(code)
                .append("&grant_type=authorization_code");
        System.out.println(url.toString());
        String results = HttpClientUtil.doGet(url.toString());
        System.out.println(results);
        return  results;
    }

    /**
     * 小程序支付回调
     *
     * @param response
     * @param request
     * @throws IOException
     */
    @RequestMapping(value = "/resultofPayForXcx")
    public String resultofPayForXcx(HttpServletResponse response, HttpServletRequest request) throws IOException {
        wxPayService.resultofPayFor(response,request);
        return null;
    }


    @RequestMapping(value = "/wxCreatOrder")
    public String wxCreatOrder(@RequestParam Map<String,String> map, HttpServletResponse response, HttpServletRequest request) throws IOException {
        JSONObject jsonObject = new JSONObject();
        try{
            String openid =map.get("openid");
            if(openid!=null&&!"".equals(openid)){
                System.out.println(map.toString());
                String orderId = map.get("orderId");//订单号
                String price = map.get("price");//价格
                String ip = getIpAddr(request);//用户真实IP地址
//                String openId = map.get("openId");//用户在小程序下的唯一标识
                String data = WxUtil.getPrepayid(orderId, (int)(Double.parseDouble(price)*100)+"", openid, ip, "【鼎瀚艺术】支付");
                System.out.println(data);
                jsonObject.put("oper_res",true);
                jsonObject.put("data",data);
            }else{
                jsonObject.put("oper_res",false);
                jsonObject.put("data","请先登录");
            }
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("oper_res",false);
            jsonObject.put("data","微信支付错误");
        }
        return jsonObject.toJSONString();
    }


    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
     *
     * @return ip
     */
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        System.out.println("x-forwarded-for ip: " + ip);
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if( ip.indexOf(",")!=-1 ){
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            System.out.println("Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            System.out.println("WL-Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
            System.out.println("HTTP_CLIENT_IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
            System.out.println("X-Real-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            System.out.println("getRemoteAddr ip: " + ip);
        }
        System.out.println("获取客户端ip: " + ip);
        return ip;
    }
}
